package vn.ugame.model.bl;

import java.sql.SQLException;
import vn.ugame.exception.*;
import vn.ugame.model.dal.AccountDA;
import vn.ugame.model.entity.Account;
import vn.ugame.model.entity.Customer;
import vn.ugame.utility.RandomString;
import vn.ugame.utility.Security;

public class Authentication {

    public void register(String email, String password, String fullName, String phoneNumber, boolean newsletter)
            throws DataConnectionFailed, SQLException, InvalidEntityClass,
            UniqueValueException {

        AccountDA accountDA = new AccountDA();
        /**
         * Check unique value
         */
        Account account = accountDA.findAccountByEmail(email);
        if (account != null) {
            throw new UniqueValueException(ExceptionCode.UNIQUE_EMAIL);
        }

        Customer customer = accountDA.findCustomerByPhoneNumber(phoneNumber);
        if (customer != null) {
            throw new UniqueValueException(ExceptionCode.UNIQUE_PHONE_NUMBER);
        }
        /**
         * MD5 password
         */
        Security security = Security.getInstance();
        password = security.getPasswordMD5(email, password);

        String uCoin = "0";

        accountDA.register(email, password, fullName, phoneNumber, newsletter, uCoin);
    }

    public void login(String email, String password)
            throws DataConnectionFailed, SQLException, InvalidEntityClass,
            EntityNotFound {

        AccountDA accountDA = new AccountDA();
        /**
         * Get account by email
         */
        Account account = accountDA.findAccountByEmail(email);
        /**
         * Check email and password is existed
         */
        if (account == null) {
            throw new EntityNotFound(ExceptionCode.LOGIN_FAILED);
        }

        Security security = Security.getInstance();
        password = security.getPasswordMD5(email, password);

        if (!account.getPassword().equals(password)) {
            throw new EntityNotFound(ExceptionCode.LOGIN_FAILED);
        }

        if (!account.isEnable()) {
            throw new EntityNotFound(ExceptionCode.DISABLE_ACCOUNT);
        }
    }
}
